package com.vans.practice.define_classloader;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author elle
 * @Date 2020/9/28 12:18
 * @Description:
 */
public class MyClassLoader extends ClassLoader {

    /**
     * 覆盖重写findClass方法
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(final String name) throws ClassNotFoundException {
        try {
            //文件名称
            String fileName = name.substring(name.lastIndexOf(".") + 1) + ".class";
            //读取class文件流
            InputStream is = this.getClass().getResourceAsStream(fileName);
            //读取字节
            byte[] b = new byte[is.available()];
            is.read(b);
            return defineClass(name, b, 0, b.length);
        } catch (IOException e) {
            throw new ClassNotFoundException();
        }
    }
}
